package org.net.cms.controller.app.application;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import org.net.cms.config.Result;
import org.net.cms.controller.app.application.vo.AppApplicationReqVO;
import org.net.cms.enums.StudentApplicationEnums;
import org.net.cms.service.application.ApplicationService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/app/application")
@Tag(name = "APP - 账号申请")
public class AppApplicationController {
    // 测试接口无误

    @Resource
    private ApplicationService applicationService;

    @PostMapping("/add")
    @Operation(summary = "新增学生入学账号申请")
    @PermitAll
    public Result addAdmissionApplication(@RequestBody AppApplicationReqVO studentReqVO) {
        int status = applicationService.checkStatus(studentReqVO.getStudentCardId());

        if (status == StudentApplicationEnums.DOES_NOT_EXIST.getStatus()) {
            // 申请不存在时创建申请
            applicationService.admissionApplication(studentReqVO);
            return Result.success();
        } else if (status == StudentApplicationEnums.PASS.getStatus()) {
            return Result.success("审核已通过，请用电话号码+身份证后六位登录！");
        } else{
            return Result.error("已申请，申请状态为：" + StudentApplicationEnums.getDescByStatus(status));
        }
    }

    @GetMapping("/get")
    @Operation(summary = "显示家长申请的某条审核的详情")
    @Parameter(name = "id", description = "审核id", required = true)
    public Result getApplication(int id) {
        return Result.success(applicationService.getApplication(id));
    }

    @GetMapping("/all")
    @Operation(summary = "显示家长申请的列表")
    public Result getMyApplicationAll() {
        // 1. 获取当前认证的 Authentication 对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        // 2. 判断是否为 UserDetails 类型（即是否已登录）
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            System.out.println(userDetails.getUsername());
            return Result.success(applicationService.getMyApplications(userDetails.getUsername()));
        }

        // 3. 如果未登录，返回错误或匿名用户
        return Result.error("用户未登录");
    }
}
